﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace makitAxeman
{
    public partial class FormMain : Form
    {
        private System.Diagnostics.EventLog _SecurityEventLogInstance;
        private AuditInfoHolder failedAccessInfo;
        private AuditInfoHolder successAccessInfo;
        private bool buttonShouldStop;
        private DateTime fromWhen;

        public FormMain()
        {
            InitializeComponent();

            _SecurityEventLogInstance = new System.Diagnostics.EventLog("Security");
            buttonShouldStop = false;

            GetLastRunTime();
        }

        private void GetLastRunTime()
        {
            string filePath = Application.StartupPath + "\\FromWhen.txt";

            if (File.Exists(filePath))
            {
                FromTextBox.Text = File.ReadAllText(filePath);
            }
        }

        private void AuditButton_Click(object sender, EventArgs e)
        {
            if (buttonShouldStop)
            {
                BackgroundWorkerAuditing.CancelAsync();
            }
            else
            {
                failedAccessInfo = new AuditInfoHolder();
                successAccessInfo = new AuditInfoHolder();

                AuditButton.Text = "Stop Auditing";
                buttonShouldStop = true;

                ProgressBarAuditing.Value = 0;
                TreeViewResults.Nodes.Clear();

                if (String.IsNullOrWhiteSpace(FromTextBox.Text))
                {
                    FromTextBox.Text = DateTime.MinValue.ToString();
                }

                fromWhen = DateTime.Parse(FromTextBox.Text);

                MessageBox.Show("Beginning to run on " + _SecurityEventLogInstance.Entries.Count.ToString() + " entries in the log.");

                BackgroundWorkerAuditing.RunWorkerAsync();
            }
        }

        private void BackgroundWorkerAuditing_DoWork(object sender, DoWorkEventArgs e)
        {
            int numberProcessed = 0;

            foreach (System.Diagnostics.EventLogEntry entry in _SecurityEventLogInstance.Entries)
            {
                if (BackgroundWorkerAuditing.CancellationPending)
                {
                    break;
                }
                else
                {
                    if (entry.TimeGenerated > fromWhen)
                    {

                        if (entry.InstanceId == 4624)
                        {
                            //4624 - Success

                            string username = entry.ReplacementStrings[5];
                            string ipAddress = entry.ReplacementStrings[19];

                            if (ipAddress.Length > 1 && ipAddress.Contains("."))
                            {
                                successAccessInfo.AddIPAccessInfo(ipAddress, null, username, entry.TimeGenerated);
                            }
                        }
                        else if (entry.InstanceId == 4625)
                        {
                            //4625 - Failure

                            string username = entry.ReplacementStrings[5];
                            string ipAddress = entry.ReplacementStrings[19];
                            string sourcePort = null;

                            if (entry.ReplacementStrings.Length >= 20)
                            {
                                sourcePort = entry.ReplacementStrings[20];
                            }

                            failedAccessInfo.AddIPAccessInfo(ipAddress, sourcePort, username, entry.TimeGenerated);
                        }

                    }

                    numberProcessed += 1;

                    int progress = Convert.ToInt32((numberProcessed / _SecurityEventLogInstance.Entries.Count) * 100);

                    BackgroundWorkerAuditing.ReportProgress(progress);
                }
            }
        }

        private void BackgroundWorkerAuditing_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressBarAuditing.Value = e.ProgressPercentage;
        }

        private void BackgroundWorkerAuditing_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // fill tree
            TreeNode failedNode = new TreeNode("Failures");
            failedNode = failedAccessInfo.AddTreeData(failedNode);
            TreeViewResults.Nodes.Add(failedNode);

            TreeNode successNode = new TreeNode("Successes");
            successNode = successAccessInfo.AddTreeData(successNode);
            TreeViewResults.Nodes.Add(successNode);

            AuditButton.Text = "Start Auditing";
            buttonShouldStop = false;
        }

        private void TreeViewResults_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == System.Windows.Forms.Keys.C) 
            {
                if (TreeViewResults.SelectedNode != null && !string.IsNullOrWhiteSpace(TreeViewResults.SelectedNode.Text) && TreeViewResults.SelectedNode.Text.Contains("."))
                {
                    string ip = TreeViewResults.SelectedNode.Text;

                    ip = ip.Substring(0, ip.IndexOf(" "));

                    TextBoxSelectedIP.Text = ip.Trim();

                    Clipboard.SetText(TextBoxSelectedIP.Text);
                }
            }
        }

        private void BuildAbuseReportButton_Click(object sender, EventArgs e)
        {
            if (failedAccessInfo != null)
            {
                string filePath = Application.StartupPath + "\\AbuseReports\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + "_AbuseReport.txt";
                File.WriteAllText(filePath, failedAccessInfo.GetAbuseData());
                MessageBox.Show("Written to " + filePath);
                FromTextBox.Text = DateTime.Now.ToString();
            }
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            string filePath = Application.StartupPath + "\\FromWhen.txt";

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            File.WriteAllText(filePath, FromTextBox.Text);
        }

    }
}
